package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhoufei
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;


    @Override
    public void remove(Long id) {
        //判断分类Id,是否有其他外键，添加查询条件，进行查询
        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Dish::getCategoryId, id);

        //执行查询
        int count1 = dishService.count(queryWrapper1);
        if (count1 > 0){
            //在菜单表中存在该id得关联信息
            //怎么处理呢？该处就表明此次删除无法成功，会报错，需要抛出异常,此时需要创建一个自定义异常类
            throw new CustomException("当前分类关联了菜品信息，无法删除");
        }

        //判断分类Id,是否有其他外键，添加查询条件，进行查询
        LambdaQueryWrapper<Setmeal> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Setmeal::getCategoryId, id);
        //执行查询
        int count2 = setmealService.count(queryWrapper2);
        if (count2 > 0){
            throw new CustomException("当前分类关联了套餐信息，无法删除");
        }

        //若没有任何关联，执行删除方法,调用父类接口中得删除方法
        super.removeById(id);
    }

}
